package com.xhwl.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.dto.cent.sdata.AttrSceneDTO;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Attr;
import com.xhwl.common.pojo.cent.sdata.AttrScene;
import com.xhwl.common.pojo.cent.sdata.AttrSceneRelation;
import com.xhwl.common.pojo.cent.sdata.Enterprise;
import com.xhwl.common.query.cent.sdata.AttrQuery;
import com.xhwl.common.query.cent.sdata.AttrSceneQuery;
import com.xhwl.data.dao.IAttrDao;
import com.xhwl.data.dao.IAttrSceneDao;
import com.xhwl.data.dao.IAttrSceneRelationDao;
import com.xhwl.data.dao.IEnterpriseDao;
import com.xhwl.data.service.IAttrSceneService;
import com.xhwl.data.service.IEnterpriseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: zhangliuli
 * @Description:
 * @Date: Create in 2023/4/13
 */
@Service
public class AttrSceneServiceImpl  extends ServiceImpl<IAttrSceneDao, AttrScene> implements IAttrSceneService {
    @Autowired
    private IEnterpriseDao enterpriseDao;
    @Autowired
    private IAttrSceneDao attrSceneDao;
    @Autowired
    private IAttrSceneRelationDao attrSceneRelationDao;
    @Autowired
    private IAttrDao attrDao;
    @Autowired
    private IAttrSceneService attrSceneService;
    @Autowired
    private IEnterpriseService enterpriseService;
    /**
     * 场景配置新增
     */
    @Override
    public ResultJson create(AttrSceneDTO attrSceneDTO) {
        // 参数校验
        if (attrSceneDTO.getName() == null || attrSceneDTO.getName().trim().length() > 6 || attrSceneDTO.getName().trim().length() == 0) {
            return ResultJson.fail("企业场景名称参数错误！");
        }
        if (attrSceneDTO.getCode() == null || attrSceneDTO.getCode().trim().length() > 18 || attrSceneDTO.getCode().trim().length() == 0) {
            return ResultJson.fail("企业场景编码参数错误！");
        }
        //检查数据库中是否已经有这个场景名称
        if (query(attrSceneDTO) != 0) {
            return ResultJson.fail("企业场景已存在！");
        }
        //检查数据库中是否已经有这个场景编码
        if (queryCode(attrSceneDTO) != 0) {
            return ResultJson.fail("企业场景编码已存在！");
        }
        if (attrSceneDTO.getEnterpriseId() == null) {
            return ResultJson.fail("运营商企业ID参数错误！");
        } else {
            Enterprise enterprise = enterpriseDao.selectById(attrSceneDTO.getEnterpriseId());
            if (null == enterprise) {
                return ResultJson.fail("该运营商企业不存在");
            }
        }
        //确定list里面的数据是否都有对应的属性
        List<Integer> attrIdList = attrSceneDTO.getAttrIdList();
        if (attrIdList.isEmpty()){
            return ResultJson.fail("参数错误，属性为空");
        }
        List<Attr> attrList = attrDao.selectList(new QueryWrapper<Attr>().in("id", attrIdList));
        if (attrIdList.isEmpty()){
            return ResultJson.fail("参数错误，选择属性已被删除");
        }
//        检查参数完毕，开始传参
//         将DTO转换为POJO
        AttrScene attrScene = attrSceneService.toAttrScene(attrSceneDTO);
        // 插入到数据库
        int result = attrSceneDao.insert(attrScene);
        if (result > 0) {
//             新增属性和场景的关系
            if (null != attrIdList && !attrIdList.isEmpty()) {
                for (Integer attrId : attrIdList) {
                    AttrSceneRelation relation = new AttrSceneRelation();
                    relation.setAttrSceneId(attrScene.getId());
                    relation.setAttrId(attrId);
                    attrSceneRelationDao.insert(relation);
                }
                return ResultJson.success("新增场景成功");
            } else {
                return ResultJson.fail("新增场景配置失败");
            }
        } else {
            return ResultJson.fail("新增场景失败");
        }
    }

    /**
     * 场景配置修改
     */
    @Override
    @Transactional
    public ResultJson update(AttrSceneDTO attrSceneDTO) {
        // 参数校验
        if (attrSceneDTO.getId() == null || attrSceneDao.selectById(attrSceneDTO.getId()) == null) {
            return ResultJson.fail("企业场景id参数错误！");
        }
        if (attrSceneDTO.getName() == null || attrSceneDTO.getName().trim().length() > 6 || attrSceneDTO.getName().trim().length() == 0) {
            return ResultJson.fail("企业场景名称参数错误！");
        }
        if (attrSceneDTO.getCode() == null || attrSceneDTO.getCode().trim().length() > 18 || attrSceneDTO.getCode().trim().length() == 0) {
            return ResultJson.fail("企业场景编码参数错误！");
        }
        if (attrSceneDTO.getEnterpriseId() == null) {
            return ResultJson.fail("运营商企业ID参数错误！");
        } else {
            Enterprise enterprise = new Enterprise();
            enterprise = enterpriseDao.selectById(attrSceneDTO.getEnterpriseId());
            if (null == enterprise) {
                return ResultJson.fail("该运营商企业不存在");
            }
        }
        //确定list里面的数据是否都有对应的属性
        List<Integer> attrIdList = attrSceneDTO.getAttrIdList();
        if (attrIdList.isEmpty()){
            return ResultJson.fail("参数错误，属性为空");
        }
        List<Attr> attrList = attrDao.selectList(new QueryWrapper<Attr>().in("id", attrIdList));
        if (attrIdList.isEmpty()){
            return ResultJson.fail("参数错误，选择属性已被删除");
        }
        //找到id对应场景数据
        AttrScene attrScene = attrSceneDao.selectById(attrSceneDTO.getId());
        if ((query(attrSceneDTO) == 0&& (queryCode(attrSceneDTO) == 0||attrSceneDTO.getCode().equals(attrScene.getCode())))|| (attrSceneDTO.getName().equals(attrScene.getName())&&(attrSceneDTO.getCode().equals(attrScene.getCode()) || queryCode(attrSceneDTO) == 0))) {

            attrScene.setCode(attrSceneDTO.getCode());
            attrScene.setName(attrSceneDTO.getName());
            attrScene.setEnterpriseId(attrSceneDTO.getEnterpriseId());
            attrScene.setRemark(attrSceneDTO.getRemark());
            // 首先删除关联的AttrSceneRelation数据
            QueryWrapper<AttrSceneRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_scene_id", attrScene.getId());
            attrSceneRelationDao.delete(queryWrapper);
            // 新增属性和场景的关系
            if (null != attrIdList && !attrIdList.isEmpty()) {
                for (Integer attrId : attrIdList) {
                    AttrSceneRelation relation = new AttrSceneRelation();
                    relation.setAttrSceneId(attrScene.getId());
                    relation.setAttrId(attrId);
                    attrSceneRelationDao.insert(relation);
                }
                attrSceneDao.updateById(attrScene);
                return ResultJson.success("修改场景成功");
            } else {
                return ResultJson.fail("场景对应属性为空");
            }
        } else {
            return ResultJson.fail("修改场景配置失败");
        }
    }

    /**
     * DTO数据传入POJO
     */
    @Override
    public AttrScene toAttrScene(AttrSceneDTO attrSceneDTO) {
        AttrScene attrScene = new AttrScene();
        attrScene.setCode(attrSceneDTO.getCode());
        attrScene.setName(attrSceneDTO.getName());
        attrScene.setEnterpriseId(attrSceneDTO.getEnterpriseId());
        attrScene.setRemark(attrSceneDTO.getRemark());
        return attrScene;
    }

    /**
     * 查询数据库表中的attrScene
     */
    @Override
    public int query(AttrSceneDTO attrSceneDTO) {
        // 先去除词语中的多余空格
        QueryWrapper<AttrScene> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("name").eq("name",attrSceneDTO.getName())
                .eq("enterprise_id",attrSceneDTO.getEnterpriseId());
        return count(queryWrapper);
    }

    /**
     * 查询数据库表中的code
     */
    @Override
    public int queryCode(AttrSceneDTO attrSceneDTO) {
        QueryWrapper<AttrScene> queryWrapper = new QueryWrapper<>();
        //场景属性编码唯一(运营商唯一)
        queryWrapper.eq("code", attrSceneDTO.getCode()).eq("enterprise_id", attrSceneDTO.getEnterpriseId());
        return count(queryWrapper);
    }

    /**
     * 配置场景删除
     */
    @Override
    public ResultJson delete(Integer id) {
        // 首先删除关联的AttrSceneRelation数据
        QueryWrapper<AttrSceneRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_scene_id", id);
        attrSceneRelationDao.delete(queryWrapper);
        // 然后再删除场景配置数据
        AttrScene attrScene = attrSceneDao.selectById(id);
        if (attrScene == null) {
            return ResultJson.fail("参数错误，数据不存在");
        } else {
            attrSceneDao.deleteById(id);
            return ResultJson.success();
        }
    }

    /**
     * 配置场景列表查询
     */
    @Override
    @Transactional
    public List<AttrScene> list(AttrSceneQuery attrSceneQuery) {
        QueryWrapper<AttrScene> query = new QueryWrapper<>();
        query.orderByDesc("created_at");
        if (null != attrSceneQuery.getName() && attrSceneQuery.getName().trim().length() != 0) {
            query.like("name", attrSceneQuery.getName());
        }
        if (attrSceneQuery.getEnterpriseId() != null) {
            query.in("enterprise_id", attrSceneQuery.getEnterpriseId());
        }
        if (attrSceneQuery.getCode() != null && attrSceneQuery.getCode().trim().length() != 0) {
            query.in("code", attrSceneQuery.getCode());
        }
        //把所有的数据放入了list
        List<AttrScene> attrSceneList = attrSceneService.list(query);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(attrSceneList)) {
            return attrSceneList;
        }
        //设置好企业通讯录的信息
        List<Integer> enterpriseIds = attrSceneList.stream().map(AttrScene::getEnterpriseId).collect(Collectors.toList());
        List<Enterprise> enterpriseList = enterpriseDao.selectList(new QueryWrapper<Enterprise>().in("id", enterpriseIds));
        Map<Integer, List<Enterprise>> enterpriseMap = new HashMap<>();
        if (!org.apache.commons.collections4.CollectionUtils.isEmpty(enterpriseList)) {
            enterpriseMap = enterpriseList.stream().collect(Collectors.groupingBy(Enterprise::getId));
        }
        //场景配置id集合
        List<Integer> attrSceneIdList = attrSceneList.stream().map(AttrScene::getId).collect(Collectors.toList());
        Map<Integer, List<Attr>> attrSceneMap = new HashMap<>();
        if (CollectionUtils.isEmpty(attrSceneIdList)) {
            return attrSceneList;
        }
        //List<AttrSceneRelation> attrSceneRelations = attrSceneRelationDao.selectBatchIds(attrSceneIdList);
        List<AttrSceneRelation> attrSceneRelations = attrSceneRelationDao.selectList(new QueryWrapper<AttrSceneRelation>().in("attr_scene_id", attrSceneIdList));
        Map<Integer, List<AttrSceneRelation>> attrSceneRelationMap = attrSceneRelations.stream().collect(Collectors.groupingBy(AttrSceneRelation::getAttrSceneId));
        attrSceneRelationMap.forEach((key, value) -> {
            List<AttrSceneRelation> attrSceneRelationList = attrSceneRelationMap.get(key);
            AttrQuery attrQuery = new AttrQuery();
            attrQuery.setIdList(attrSceneRelationList.stream().map(AttrSceneRelation::getAttrId).collect(Collectors.toList()));
            List<Attr> attrs = attrDao.list(attrQuery);
            // 抽出attrs的企业id，查询企业list数据，根据企业list转map，再进行赋值
            //按照attr&relation排序
            List<Integer> attrIds = attrSceneRelationMap.get(key).stream().map(AttrSceneRelation::getAttrId).collect(Collectors.toList());
            ArrayList<Attr> filterAttrs = new ArrayList<>();
            for (Integer attrId : attrIds) {
                List<Attr> list = attrs.stream().filter(p -> p.getId().equals(attrId)).collect(Collectors.toList());
                filterAttrs.addAll(list);
            }

            //设置好企业通讯录的信息
            List<Integer> enterpriseIds2 = attrs.stream().map(Attr::getEnterpriseId).collect(Collectors.toList());
            List<Enterprise> enterpriseList2 = enterpriseDao.selectList(new QueryWrapper<Enterprise>().in("id", enterpriseIds2));
            Map<Integer, List<Enterprise>> enterpriseMap2 = new HashMap<>();
            if (!org.apache.commons.collections4.CollectionUtils.isEmpty(enterpriseList2)) {
                enterpriseMap2 = enterpriseList2.stream().collect(Collectors.groupingBy(Enterprise::getId));
            }
            //把企业名字放到attrs里面去
            for (Attr attr : filterAttrs) {
                if (!CollectionUtils.isEmpty(enterpriseMap2.get(attr.getEnterpriseId()))) {
                    attr.setEnterpriseName(enterpriseMap2.get(attr.getEnterpriseId()).get(0).getName());
                }
            }
            attrSceneMap.put(key, filterAttrs);
        });
        for (AttrScene attrScene : attrSceneList) {
            if (!CollectionUtils.isEmpty(enterpriseMap.get(attrScene.getEnterpriseId()))) {
                attrScene.setEnterpriseName(enterpriseMap.get(attrScene.getEnterpriseId()).get(0).getName());
            }
            if (!CollectionUtils.isEmpty(attrSceneMap.get(attrScene.getId()))) {
                attrScene.setAttrList(attrSceneMap.get(attrScene.getId()));
            }
        }
        return attrSceneList;
    }

    /**
     * 配置场景分页查询
     */
    @Override
    public Page<AttrScene> page(Page page, AttrSceneQuery attrSceneQuery) {
        QueryWrapper<AttrScene> query = new QueryWrapper<>();
        query.orderByDesc("created_at");
        if (null != attrSceneQuery.getName() && attrSceneQuery.getName().trim().length() != 0) {
            query.like("name", attrSceneQuery.getName());
        }
        if (attrSceneQuery.getEnterpriseId() != null) {
            query.in("enterprise_id", attrSceneQuery.getEnterpriseId());
        }
        if (attrSceneQuery.getCode() != null && attrSceneQuery.getCode().trim().length() != 0) {
            query.in("code", attrSceneQuery.getCode());
        }
        Page page1 = attrSceneDao.selectPage(page, query);
//        List<AttrScene> records = page.getRecords();
//        List<AttrScene> attrSceneList = attrSceneService.list(query);
        List<AttrScene> attrSceneList = page.getRecords();
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(attrSceneList)) {
            return page1;
        }
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(attrSceneList)) {
            return page1;
        }
        //设置好企业通讯录的信息
        List<Integer> enterpriseIds = attrSceneList.stream().map(AttrScene::getEnterpriseId).collect(Collectors.toList());
        List<Enterprise> enterpriseList = enterpriseDao.selectList(new QueryWrapper<Enterprise>().in("id", enterpriseIds));
        Map<Integer, List<Enterprise>> enterpriseMap = new HashMap<>();
        if (!org.apache.commons.collections4.CollectionUtils.isEmpty(enterpriseList)) {
            enterpriseMap = enterpriseList.stream().collect(Collectors.groupingBy(Enterprise::getId));
        }
        //场景配置id集合
        List<Integer> attrSceneIdList = attrSceneList.stream().map(AttrScene::getId).collect(Collectors.toList());
        Map<Integer, List<Attr>> attrSceneMap = new HashMap<>();
        if (CollectionUtils.isEmpty(attrSceneIdList)) {
            return page1;
        }
        //List<AttrSceneRelation> attrSceneRelations = attrSceneRelationDao.selectBatchIds(attrSceneIdList);
        List<AttrSceneRelation> attrSceneRelations = attrSceneRelationDao.selectList(new QueryWrapper<AttrSceneRelation>().in("attr_scene_id", attrSceneIdList));
        Map<Integer, List<AttrSceneRelation>> attrSceneRelationMap = attrSceneRelations.stream().collect(Collectors.groupingBy(AttrSceneRelation::getAttrSceneId));
        attrSceneRelationMap.forEach((key, value) -> {
            List<AttrSceneRelation> attrSceneRelationList = attrSceneRelationMap.get(key);
            AttrQuery attrQuery = new AttrQuery();
            attrQuery.setIdList(attrSceneRelationList.stream().map(AttrSceneRelation::getAttrId).collect(Collectors.toList()));
            List<Attr> attrs = attrDao.list(attrQuery);
            // 抽出attrs的企业id，查询企业list数据，根据企业list转map，再进行赋值
            //按照attr&relation排序
            List<Integer> attrIds = attrSceneRelationMap.get(key).stream().map(AttrSceneRelation::getAttrId).collect(Collectors.toList());
            ArrayList<Attr> filterAttrs = new ArrayList<>();
            for (Integer attrId : attrIds) {
                List<Attr> list = attrs.stream().filter(p -> p.getId().equals(attrId)).collect(Collectors.toList());
                filterAttrs.addAll(list);
            }
            //设置好企业通讯录的信息
            List<Integer> enterpriseIds2 = attrs.stream().map(Attr::getEnterpriseId).collect(Collectors.toList());
            List<Enterprise> enterpriseList2 = enterpriseDao.selectList(new QueryWrapper<Enterprise>().in("id", enterpriseIds2));
            Map<Integer, List<Enterprise>> enterpriseMap2 = new HashMap<>();
            if (!org.apache.commons.collections4.CollectionUtils.isEmpty(enterpriseList2)) {
                enterpriseMap2 = enterpriseList2.stream().collect(Collectors.groupingBy(Enterprise::getId));
            }
            //把企业名字放到attrs里面去
            for (Attr attr : filterAttrs) {
                if (!CollectionUtils.isEmpty(enterpriseMap2.get(attr.getEnterpriseId()))) {
                    attr.setEnterpriseName(enterpriseMap2.get(attr.getEnterpriseId()).get(0).getName());
                }
            }
            attrSceneMap.put(key, filterAttrs);
        });
        for (AttrScene attrScene : attrSceneList) {
            if (!CollectionUtils.isEmpty(enterpriseMap.get(attrScene.getEnterpriseId()))) {
                attrScene.setEnterpriseName(enterpriseMap.get(attrScene.getEnterpriseId()).get(0).getName());
            }
            if (!CollectionUtils.isEmpty(attrSceneMap.get(attrScene.getId()))) {
                attrScene.setAttrList(attrSceneMap.get(attrScene.getId()));
            }
        }
        return page1;
    }
}
